<?php
/**
 * Глобальный класс управления тегами материалов сайта
 * 
 * @category Phorm
 * @package Tags
 * @name /Phorm/Tags.php
 * @copyright phorm.ru
 * @since 22.12.2010
 * @author vladimir@kachalov.net
 */

class Phorm_Tags extends Phorm_Model {
	
	/**
	 * Возвращает облако тегов
	 * 
	 * @param array $opions Массив опций
	 * 
	 * @return array
	 */
		
	function getTagsCloud($options=array()) {
		
		$select = $this->_db->select()
				-> from(array("AA"=>"pw_tags"),array("tagid","tagname"))
				-> join(array("BB"=>"pw_resources_tags"),"AA.tagid=BB.tagid",array("score"=>"COUNT(BB.tagid)"))
				-> join(array("CC"=>"pw_resources"),"BB.resourceid=CC.resourceid")
				-> where("CC.isexist='yes'")
				-> group("AA.tagid")
				-> order("AA.tagname");
				
		if($this->_module!="control") {
			$select -> where("AA.visible='yes'")
					-> where("CC.visible='yes'");
		}
			
		if(isset($options["rowsperpage"]) && $options["rowsperpage"]>0) $select -> limit((int)$options["rowsperpage"]);
			
		if($rows = $this->_db->fetchAll($select)) {
				
			$totalscore = 0;
			foreach ($rows as $key => $row) $totalscore += $row["score"];
			foreach ($rows as $key => $row) $rows[$key]["score"] = $row["score"]/$totalscore*100;
				
			return $rows;
				
		}
			
		return false;
			
	}
		
		
	/**
	 * Возвращает информацию о теге
	 * 
	 * @param int $tagid Id тега
	 * 
	 * @return array
	 */
		
	public function getTagInfo($tagid) {
		
		$select = $this->_db->select()
				-> from(array("AA"=>"pw_tags"),array("tagid","tagname","score"=>"COUNT(BB.tagid)"))
				-> joinLeft(array("BB"=>"pw_resources_tags"),"AA.tagid=BB.tagid")
				-> joinLeft(array("CC"=>"pw_resources"),"BB.resourceid=CC.resourceid")
				-> where("AA.visible='yes'")
				-> where("AA.tagid=".(int)$tagid)
				-> group("AA.tagid");
			
		return $this->_db->fetchRow($select);
			
	}
		
		
	/**
	 * Возвращает список материалов по тегу
	 * 
	 * @param int $tagid Id тега
	 * 
	 * @return array
	 */
		
	public function getSearchResults($tagid) {
		
		$Resource = new Phorm_Resource();
			
		return $Resource->getResourcesList(array("tags"=>array($tagid)));
			
	}
	
}
